package com.sqx.modules.userGetPhoneRecord.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.enums.CommonStatus;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.postPush.entity.PostPush;
import com.sqx.modules.postPush.service.PostPushService;
import com.sqx.modules.userGetPhoneRecord.entity.UserGetPhoneRecord;
import com.sqx.modules.userGetPhoneRecord.dao.UserGetPhoneRecordDao;
import com.sqx.modules.userGetPhoneRecord.service.IUserGetPhoneRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.modules.userGetPhoneRecord.vo.UserGetPhoneRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * 用户购买记录表 服务实现类
 * </p>
 *
 * @author wuchang
 * @since 2023-07-05
 */
@Service
public class UserGetPhoneRecordServiceImpl extends ServiceImpl<UserGetPhoneRecordDao, UserGetPhoneRecord> implements IUserGetPhoneRecordService {

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Autowired
    private UserMoneyService moneyService;
    @Autowired
    private PostPushService postPushService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserMoneyDetailsService detailsService;
    @Autowired
    private IUserGetPhoneRecordService recordService;
    @Autowired
    private UserService userService;

    @Override
    public Result buyPhone(Long userId, Long postPushId) {
        CommonInfo isAuth = commonInfoService.findOne(344);
        UserEntity userEntity = userService.getById(userId);
        if ("是".equals(isAuth.getValue())) {
            if (userEntity.getCheckCertification() != 1) {
                return Result.error(CommonStatus.NOT_AUTHENTICATION.getCode(), CommonStatus.NOT_AUTHENTICATION.getInfo());
            }
        }
        reentrantReadWriteLock.readLock().lock();
        try {
            int count = baseMapper.selectCount(new QueryWrapper<UserGetPhoneRecord>().eq("user_id", userId).eq("post_push_id", postPushId));
            if (count > 0) {
                //重复购买
                return Result.error(CommonStatus.BUY_REPEAT.getCode(), CommonStatus.BUY_REPEAT.getInfo());
            } else {
                PostPush postPush = postPushService.getById(postPushId);
                if (postPush.getStatus() == 4) {
                    //当前数据已被封禁
                    return Result.error(CommonStatus.DATA_BAN.getCode(), CommonStatus.DATA_BAN.getInfo());
                }
                if (postPush.getStatus() == 3) {
                    //已找到工人
                    return Result.error(CommonStatus.NOT_NEED.getCode(), CommonStatus.NOT_NEED.getInfo());
                }
                UserMoney userMoney = moneyService.getOne(new QueryWrapper<UserMoney>().eq("user_id", userId));
                BigDecimal price = new BigDecimal(commonInfoService.findOne(342).getValue());
                if (userMoney.getMoney().compareTo(price) >= 0) {
                    moneyService.updateMoney(2, userId, price);
                    UserMoneyDetails moneyDetails = new UserMoneyDetails();
                    moneyDetails.setUserId(userId);
                    moneyDetails.setTitle("支付成功");
                    moneyDetails.setContent("花费" + price + "积分获取手机号:" + postPush.getPhone());
                    moneyDetails.setType(2);
                    moneyDetails.setClassify(2);
                    moneyDetails.setState(2);
                    moneyDetails.setMoney(price);
                    moneyDetails.setCreateTime(DateUtils.format(new Date()));
                    detailsService.save(moneyDetails);
                    UserGetPhoneRecord userGetPhoneRecord = new UserGetPhoneRecord();
                    userGetPhoneRecord.setUserId(userId);
                    userGetPhoneRecord.setPostPushId(postPushId);
                    userGetPhoneRecord.setMoney(price);
                    userGetPhoneRecord.setType(postPush.getType());
                    userGetPhoneRecord.setCreateTime(LocalDateTime.now());
                    return recordService.save(userGetPhoneRecord) ? Result.success() : Result.error();

                } else {
                    return Result.error(CommonStatus.BALANCE_FUNDS.getCode(), CommonStatus.BALANCE_FUNDS.getInfo());
                }

            }
        } catch (Exception e) {
            log.error("购买异常" + e.getMessage());
        } finally {
            reentrantReadWriteLock.readLock().unlock();
        }
        return Result.error("购买异常,请重试");

    }

    @Override
    public Result getPostPushPhone(Long userId, Long postPushId) {

        UserGetPhoneRecord record = baseMapper.selectOne(new QueryWrapper<UserGetPhoneRecord>().eq("user_id", userId).eq("post_push_id", postPushId));
        if (record != null) {
            PostPush postPush = postPushService.getById(postPushId);
            return Result.success().put("data", postPush.getPhone());
        } else {
            return Result.error(CommonStatus.NOT_BUY.getCode(), CommonStatus.NOT_BUY.getInfo());
        }


    }

    @Override
    public IPage<UserGetPhoneRecordVo> getByPhoneList(Integer page, Integer limit, UserGetPhoneRecordVo phoneRecordVo) {
        Page<UserGetPhoneRecordVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getByPhoneList(pages, phoneRecordVo);
    }
}
